import { CaptureScreenshotService } from '@/common/capture_screenshot'
import { askBg } from '@/ext/ipc'
import { getScreenshotInSearchArea } from '@/common/search_vision'
import { getPageDpi } from '@/common/utils'

export const replaceEscapedChar = (str: string, command: any, field: string, shouldEscape = true) => {
  if (!shouldEscape) {
    return str
  }

  if (
    [
      'csvRead',
      'csvReadArray',
      'csvSave',
      'gotoIf',
      'if',
      'while',
      'elseif',
      'repeatIf',
      'executeScript',
      'executeScript_Sandbox',
      'executeAsyncScript',
      'executeAsyncScript_Sandbox'
    ].indexOf(command.cmd) !== -1 &&
    field === 'target'
  ) {
    return str
  }

  if (['csvSaveArray'].indexOf(command.cmd) !== -1 && field === 'value') {
    return str
  }

  return [
    [/\\n/g, '\n'],
    [/\\t/g, '\t'],
    [/\\b/g, '\b'],
    [/\\f/g, '\f'],
    [/\\t/g, '\t'],
    [/\\v/g, '\v']
  ].reduce((prev, [reg, c]) => {
    return prev.replace(reg, c)
  }, str)
}

export const captureImage = async (args: any) => {
  console.log('captureImage args >>>', args)
  const { searchArea, storedImageRect, scaleDpi, devicePixelRatio } = args
  const captureScreenshotService = new CaptureScreenshotService({
    captureVisibleTab: (windowId, options) => askBg('PANEL_CAPTURE_VISIBLE_TAB', { windowId, options })
  })

  return getScreenshotInSearchArea({
    searchArea,
    storedImageRect,
    devicePixelRatio,
    captureScreenshotService,
    dpiScale: scaleDpi ? 96 / getPageDpi() : 1
  })
}


export const withVisualHighlightHidden = (fn: any) => {
  const hide = () => askBg('PANEL_HIDE_VISION_HIGHLIGHT').catch(() => { })
  const show = () => askBg('PANEL_SHOW_VISION_HIGHLIGHT').catch(() => { })

  return hide()
    .then(() => fn())
    .then(
      (data: any) => {
        show()
        return data
      },
      (e: any) => {
        show()
        throw e
      }
    )
}